import { ElMessage } from 'element-plus'
import { useI18n } from 'vue-i18n'

/**
 * API错误处理工具
 */
export class ApiErrorHandler {
  private static instance: ApiErrorHandler
  private i18n: any

  private constructor() {
    // 在组件中使用时会重新设置
    this.i18n = null
  }

  public static getInstance(): ApiErrorHandler {
    if (!ApiErrorHandler.instance) {
      ApiErrorHandler.instance = new ApiErrorHandler()
    }
    return ApiErrorHandler.instance
  }

  /**
   * 设置国际化实例
   */
  public setI18n(i18n: any) {
    this.i18n = i18n
  }

  /**
   * 处理API响应错误
   */
  public handleApiError(error: any, defaultMessage?: string): string {
    let errorMessage = defaultMessage || '操作失败'

    if (error) {
      // 如果是API响应错误
      if (error.response) {
        const { status, data } = error.response
        
        switch (status) {
          case 400:
            errorMessage = data?.message || '请求参数错误'
            break
          case 401:
            errorMessage = '未授权，请重新登录'
            // 可以在这里触发登录跳转
            break
          case 403:
            errorMessage = '权限不足'
            break
          case 404:
            errorMessage = '请求的资源不存在'
            break
          case 500:
            errorMessage = '服务器内部错误'
            break
          default:
            errorMessage = data?.message || `请求失败 (${status})`
        }
      } 
      // 如果是网络错误
      else if (error.code === 'NETWORK_ERROR') {
        errorMessage = '网络连接失败，请检查网络设置'
      }
      // 如果是超时错误
      else if (error.code === 'TIMEOUT') {
        errorMessage = '请求超时，请稍后重试'
      }
      // 如果有错误消息
      else if (error.message) {
        errorMessage = error.message
      }
    }

    return errorMessage
  }

  /**
   * 显示错误消息
   */
  public showError(error: any, defaultMessage?: string) {
    const message = this.handleApiError(error, defaultMessage)
    ElMessage.error(message)
  }

  /**
   * 处理API响应
   */
  public handleApiResponse<T>(response: any): T {
    if (response.code !== 200) {
      throw new Error(response.message || '请求失败')
    }
    return response.data
  }

  /**
   * 包装异步API调用
   */
  public async wrapApiCall<T>(
    apiCall: () => Promise<any>,
    options: {
      loadingRef?: { value: boolean }
      successMessage?: string
      errorMessage?: string
      showSuccess?: boolean
    } = {}
  ): Promise<T | null> {
    const { loadingRef, successMessage, errorMessage, showSuccess = false } = options

    try {
      if (loadingRef) {
        loadingRef.value = true
      }

      const response = await apiCall()
      const data = this.handleApiResponse<T>(response)

      if (showSuccess && successMessage) {
        ElMessage.success(successMessage)
      }

      return data
    } catch (error) {
      this.showError(error, errorMessage)
      return null
    } finally {
      if (loadingRef) {
        loadingRef.value = false
      }
    }
  }
}

/**
 * 创建错误处理器实例
 */
export function createErrorHandler() {
  const errorHandler = ApiErrorHandler.getInstance()
  
  // 在组件中使用时设置国际化
  try {
    const { t } = useI18n()
    errorHandler.setI18n({ t })
  } catch (error) {
    // 如果不在组件上下文中，忽略错误
  }

  return errorHandler
}

/**
 * 快捷方法：处理API错误
 */
export function handleApiError(error: any, defaultMessage?: string): string {
  return ApiErrorHandler.getInstance().handleApiError(error, defaultMessage)
}

/**
 * 快捷方法：显示错误消息
 */
export function showApiError(error: any, defaultMessage?: string) {
  ApiErrorHandler.getInstance().showError(error, defaultMessage)
}

/**
 * 快捷方法：处理API响应
 */
export function handleApiResponse<T>(response: any): T {
  return ApiErrorHandler.getInstance().handleApiResponse<T>(response)
}

/**
 * 快捷方法：包装API调用
 */
export function wrapApiCall<T>(
  apiCall: () => Promise<any>,
  options: {
    loadingRef?: { value: boolean }
    successMessage?: string
    errorMessage?: string
    showSuccess?: boolean
  } = {}
): Promise<T | null> {
  return ApiErrorHandler.getInstance().wrapApiCall<T>(apiCall, options)
}

/**
 * 错误类型枚举
 */
export enum ErrorType {
  NETWORK = 'NETWORK_ERROR',
  TIMEOUT = 'TIMEOUT',
  UNAUTHORIZED = 'UNAUTHORIZED',
  FORBIDDEN = 'FORBIDDEN',
  NOT_FOUND = 'NOT_FOUND',
  SERVER_ERROR = 'SERVER_ERROR',
  VALIDATION = 'VALIDATION_ERROR',
  UNKNOWN = 'UNKNOWN_ERROR'
}

/**
 * 自定义错误类
 */
export class ApiError extends Error {
  public type: ErrorType
  public code?: number
  public details?: any

  constructor(
    message: string,
    type: ErrorType = ErrorType.UNKNOWN,
    code?: number,
    details?: any
  ) {
    super(message)
    this.name = 'ApiError'
    this.type = type
    this.code = code
    this.details = details
  }
}
